package com.sc.sysconfig.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.sysconfig.client.SysConfigClient;
import com.sc.sysconfig.dto.EditPasswordDTO;
import com.sc.sysconfig.dto.UserLoginDTO;
import com.sc.sysconfig.dto.UserQueryDTO;
import com.sc.sysconfig.entity.SysUser;
import com.sc.sysconfig.service.impl.SysUserServiceImpl;
import com.sc.sysconfig.util.ShaPWD;
import com.sc.sysconfig.util.Token;
import com.sc.sysconfig.vo.PageVO;
import com.sc.sysconfig.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 系统用户控制器
 *
 * @author 徐赫阳
 * @date 2021/08/30
 */
@Api(description = "用户")
@RestController
@RequestMapping("/user")
public class SysUserController {

    /**
     * 服务对象
     */
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysConfigClient client;

    @ApiOperation("分页获取用户")
    @PostMapping("/getUserList")
        public PageVO<SysUser> getUserList(@RequestBody UserQueryDTO queryDTO){
        return sysUserService.getUserList(queryDTO);
    }

    @ApiOperation("根据id获取用户")
    @GetMapping("/getUserById/{id}")
    public SysUser getUserById(@PathVariable Integer id){
        return sysUserService.getById(id);
    }

    @ApiOperation("根据id获取用户")
    @GetMapping("/getUserByLoginName/{loginName}")
    public SysUser getUserByLoginName(@PathVariable String loginName){
        QueryWrapper<SysUser> q = new QueryWrapper<>();
        q.lambda().eq(SysUser::getLoginName,loginName);
        return sysUserService.getOne(q);
    }

    @ApiOperation("保存用户")
    @PostMapping("/saveUser")
    public Integer saveUser(@RequestBody SysUser sysUser, HttpServletRequest request) throws Exception{
        if(sysUser.getId() == null){
            sysUser.setCreatorId((Integer)request.getSession(true).getAttribute("user"));
            QueryWrapper<SysUser> q = new QueryWrapper<>();
            q.lambda().eq(SysUser::getLoginName,sysUser.getLoginName());
            List<SysUser> users = sysUserService.list(q);
            if(users != null && !users.isEmpty()){
                throw new Exception("该账号已存在！请更换账号后重新提交");
            }
            sysUser.setPassword(ShaPWD.getSHA256("123456"));
        }else{
            sysUser.setUpdaterId((Integer)request.getSession(true).getAttribute("user"));
            QueryWrapper<SysUser> q = new QueryWrapper<>();
            q.lambda().eq(SysUser::getLoginName,sysUser.getLoginName()).ne(SysUser::getId,sysUser.getId());
            List<SysUser> users = sysUserService.list(q);
            if(users != null && !users.isEmpty()){
                throw new Exception("该账号已存在！请更换账号后重新提交");
            }
        }
        sysUserService.saveOrUpdate(sysUser);
        return sysUser.getId();
    }

    @ApiOperation("保存用户（头像）")
    @PostMapping(value = "/saveAvatar")
    public void saveAvatar(@RequestBody SysUser user) throws Exception{
        QueryWrapper<SysUser> q = new QueryWrapper<>();
        q.lambda().eq(SysUser::getLoginName,user.getLoginName());
        SysUser u = sysUserService.list(q).get(0);
        u.setAvatar(user.getAvatar());
        sysUserService.saveOrUpdate(u);
    }

    @ApiOperation("登录")
    @PostMapping(value = "/login")
    public String login(@RequestBody UserLoginDTO user, HttpServletRequest request) throws Exception{
        user.setPassword(ShaPWD.getSHA256(user.getPassword()));
        SysUser u = sysUserService.login(user);
        System.out.println(JSON.toJSONString(u));
        if (u == null){
            throw new Exception("账号名或密码错误");
        }else{
            Map<String,Object> map = new HashMap();
            map.put("userName",u.getLoginName());
            map.put("userId",u.getId());
            HttpSession session = request.getSession();
            session.setAttribute("user",u.getId());
            return Token.createToken(map);
        }
    }

    @ApiOperation("删除")
    @DeleteMapping(value = "/deleteUser/{id}")
    public void deleteUser(@PathVariable Integer id) throws Exception{
        sysUserService.removeById(id);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/editPassword")
    public void editPassword(@RequestBody EditPasswordDTO edit, HttpServletRequest request) throws Exception{
        UserLoginDTO user = new UserLoginDTO();
        user.setLoginName(edit.getLoginName());
        user.setPassword(ShaPWD.getSHA256(edit.getPasswordOld()));
        SysUser u = sysUserService.login(user);
        if (u == null){
            throw new Exception("旧密码输入错误");
        }else{
            u.setPassword(ShaPWD.getSHA256(edit.getPassword()));
            sysUserService.saveOrUpdate(u);
        }
    }

}
